package config

import (
	"gopkg.in/yaml.v3"
	"kf/utils/R"
	"log"
	"os"
	"path"
)

type Conf struct {
	Svc         server    `yaml:"server"`
	DB          database  `yaml:"database"`
	RedisConfig redis     `yaml:"redis"`
	Jwt         jwt       `yaml:"jwt"`
	LogConfig   logConfig `yaml:"log"`
	Ws          ws        `yaml:"ws"`
}

type server struct {
	Port           int    `yaml:"port"`
	RunMode        string `yaml:"runMode"`
	LogLevel       string `yaml:"logLevel"`
	EnabledSwagger bool   `yaml:"enabledSwagger"`
}

type database struct {
	Type            string `yaml:"type"`
	Host            string `yaml:"host"`
	Port            string `yaml:"port"`
	UserName        string `yaml:"username"`
	Password        string `yaml:"password"`
	DbName          string `yaml:"dbname"`
	MaxIdleConn     int    `yaml:"max_idle_conn"`
	MaxOpenConn     int    `yaml:"max_open_conn"`
	ConnMaxLifetime int    `yaml:"conn_max_lifetime"`
}

type redis struct {
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
	Password string `yaml:"password"`
	DB       int    `yaml:"db"`
}

type jwt struct {
	Secret string `yaml:"secret"`
	JwtTtl int    `yaml:"jwt_ttl"`
}

type ws struct {
	TimerInterval int     `yaml:"timerInterval"`
	VisitorExpire float64 `yaml:"visitorExpire"`
}

type logConfig struct {
	Enabled  bool     `yaml:"enabled"`
	LogMode  string   `yaml:"logMode"`
	FilePath string   `yaml:"filePath"`
	Filtered []string `yaml:"filtered"`
}

// 初始化app配置
func InitAppConfig(dataFile string) *Conf {
	// 解决相对路经下获取不了配置文件问题
	//_, filename, _, _ := runtime.Caller(0)
	filePath := path.Join("", dataFile)

	//filePath := dataFile
	_, err := os.Stat(filePath)
	if err != nil {
		log.Printf("config file path %s not exist", filePath)
		panic(R.ReturnFailMsg("config file path " + filePath + " not exist"))
	}
	yamlFile, err := os.ReadFile(filePath)
	if err != nil {
		log.Printf("yamlFile.Get err   #%v ", err)
		panic(R.ReturnFailMsg("yamlFile.Get err   " + err.Error()))
	}
	c := new(Conf)
	err = yaml.Unmarshal(yamlFile, &c)
	if err != nil {
		log.Printf("Unmarshal: %v", err)
		panic("Unmarshal:" + err.Error())
	}
	log.Printf("load conf success")
	return c
}
